﻿using PIMS.Interface;
using PIMS.Utils;
using PIMS.XmlModel;
using PIMS.XmlModel.Snap7;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PIMS
{
    /// <summary>
    /// SunYu Add
    /// </summary>
    public partial class IOMonitor : Form
    {
        private List<TemplateData> VariableList;
        private string DeviceIP;
        private string PLCType;
        private ICommunication IC;
        private int SignalNum;
        private IPLCXModel s7Model;

        private BackgroundWorker bgw1 = null;

        public IOMonitor()
        {
            InitializeComponent();
        }

        public IOMonitor(ICommunication ic, IPLCXModel s7)
        {
            InitializeComponent();

            this.bgw1 = new BackgroundWorker();
            this.bgw1.DoWork += (s, e) => GetPlcData();
            this.bgw1.RunWorkerCompleted += (s, e) => ReadPLCEnd();

            SignalNum = s7.PLC.Num;
            IC = ic;
            s7Model = s7;
            VariableList = new List<TemplateData>(SignalNum);
        }

        private void IOMonitor_Load(object sender, EventArgs e)
        {
            dgvIOMonitor.Rows.Add(SignalNum);
            int id;
            string db, addr, type, name = string.Empty;
            foreach (XItemsID items in s7Model.PLC.itemsID)
            {
                id = items.id;
                db = items.db;
                addr = items.addr;
                type = items.type;
                name = items.name;
                VariableList.Add(new TemplateData(id, db, addr, type, name, null));
            }
            string str = string.Empty;
            for (int i = 0; i < SignalNum; i++)
            {
                str = $"Id:{VariableList[i].Id}  Name:{VariableList[i].Name}";
                dgvIOMonitor[0, i].Value = str;
            }
            timer1.Enabled = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ReadPLCEnd()
        {
            try
            {
               // GetPlcData();
                UpdateDGV();
                DgvTools.dataGridViewAutoSize(dgvIOMonitor);
                btn_PLCRead.Enabled = true;
                this.timer1.Enabled = false;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.StackTrace,ex.Message);
            }

        }

        private void UpdateDGV()
        {
            for (int i = 0; i < SignalNum; i++)
            {
                dgvIOMonitor[1, i].Value = VariableList[i].Result;
            }
            DgvTools.dataGridViewAutoSize(dgvIOMonitor);
        }

        private void GetPlcData()
        {
            int count = 0;
            try
            {
                bool result;
                int i = 0;
                foreach (XItemsID items in s7Model.PLC.itemsID)
                {
                    if (items.type == "bool")
                    {
                        VariableList[i].Result = (IC.Read<bool>(items.id, out result)).ToString();
                    }
                    else if (items.type == "string"|| items.type == "wstring")
                    {
                        VariableList[i].Result = IC.Read<string>(items.id, out result);
                    }
                    else if (items.type == "int")
                    {
                        VariableList[i].Result = (IC.Read<int>(items.id, out result)).ToString();
                    }
                    else if (items.type == "byte")
                    {
                        VariableList[i].Result = "0x"+(IC.Read<byte>(items.id, out result)).ToString("x2");
                    }
                    else if (items.type == "byte[]")
                    {
                        VariableList[i].Result = BitConverter.ToString(IC.Read<byte[]>(items.id, out result));
                    }
                    else if (items.type == "real")
                    {
                        VariableList[i].Result = (IC.Read<Single>(items.id, out result)).ToString();
                    }
                    i++;
                    count++;
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine("PLC读取失败：" + ex.Message);
                Common.d.DebugMsg($"itemId={count} read Error!");
                Common.log.Error($"itemId={count} read Error!", ex);
                throw ex;
            }
        }

        private void btn_PLCRead_Click(object sender, EventArgs e)
        {
            if(!IC.IsConnected)
            {
                MessageBox.Show("PLC离线!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            this.timer1.Enabled= true;
            btn_PLCRead.Enabled = false;
            // ReadPLC();
            if (this.bgw1.IsBusy)
            {
                return;
            }
             this.bgw1.RunWorkerAsync();

        }
    }
    /// <summary>
    /// SunYu Add
    /// </summary>
    public class TemplateData
    {
        public int Id;
        public string Db;
        public string Addr;
        public string Type;
        public string Name;
        public string Result;
        public TemplateData(int id, string db, string addr, string type, string name, string result)
        {
            Id = id;
            Db = db;
            Addr = addr;
            Type = type;
            Name = name;
            Result = result;
        }
    }
}
